<?php

/**
 * Default UserController
 *
 * 拾光 ysu图书馆系统的用户登录管理的统一类  UserController
 *
 * @package 	laravel
 * @subpackage	app/controllers
 * @version 	1.0.0
 */

class UserController extends BaseController {

	public $data = array();            //传入view的数据

	/**
	 * 构造函数
	 *
	 */
	public function __construct(){

		session_start();

	}


	/**
	 * Session判断的统一接口
	 *
	 * @access 		public static
	 * @param
	 * @return
	 */
	public static function check_session(){

	}




	/**
     * @api {get} /pre GetPrePic
     * @apiVersion 0.2.0
     * @apiName GetPrePic
     * @apiGroup User
     * @apiPermission app
     *
     * @apiDescription 可获取登陆时的验证码
     *
     * @apiSuccess {Boolean}  error 是否错误.
     * @apiSuccess {String}   result.session 用户的session.
     * @apiSuccess {String}   result.pic 验证码的base64编码.
     * @apiSuccess {String}   message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.179:82/pre
     */
	public function pre(){

		if( empty($_SESSION['user_id']) ){
			return Response::json(['error'=>true , 'message'=>'请先登录或退出页面后重试'] , 200);
        }else{
			$user_id = $_SESSION['user_id'];
			$arr = array(
				'method' => 'GET' ,
				'path' => 'pre' ,
				'query' => array()
				);
			$uri = Config::get('lib.ptime_api')."/user/".$user_id."/system_cat/library/api";
			$verify = $this->curl_post( $uri , $arr , "campus" , "" );
			$verify_result = json_decode($verify , true);

			if( isset($verify_result['error']) ){
				if( $verify_result['error'] ){
					return Response::json(['error'=>true , 'message'=>'请求失败，暂时无法登录'] , 200);
				}else{
					return Response::json(['error'=>false , 'pic'=>$verify_result['result']['code_row']] , 200);
				}
			}
		}


		// include( app_path()."/libraries/Snoopy.class.php");
		// ini_set("max_execution_time" , 18000);
		//
		//
		// $agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36';//伪装浏览器
		// $library_ip = "202.206.242.99";
		// $library_host = "http://202.206.242.99/";
		// $library_pic_router = "reader/captcha.php";
		// $library_login_router = "reader/login.php";
		//
		// $snoopy = new Snoopy;
		// $submit_url = $library_host.$library_pic_router;
		//
		// //获取cookie
		// $snoopy->host = $library_ip;
		// $snoopy->agent = $agent;
		// $snoopy->fetch($submit_url);
		// $snoopy->setcookies();
		// $cookie = $snoopy->cookies;
		// //超时返回
		// if ($snoopy->status != '200' || $snoopy->timed_out)
	    // 	return Response::json( ['error'=>true , 'message'=>'获取验证码失败'] , 200 );
		//
		// $result = $snoopy->results;
		//
		// $pic_data = "data:image/gif;base64,".base64_encode($result);
		// Session::put('pre_session' , $cookie['PHPSESSID']);
		//
		// return Response::json( ['error'=>false , 'session'=>$cookie , 'pic'=>$pic_data] , 200 );
	}


	public function extraPre(){
		include( app_path()."/libraries/Snoopy.class.php");
		ini_set("max_execution_time" , 18000);

		if( !Session::has('user_id') ){
			return Response::json(['error'=>true , 'message'=>'用户身份过期，请重新登陆'] , 200);
		}
		$user_id = Session::get('user_id');

		$user_info = DB::table('user')->where('id' , '=' , $user_id)->get();
		if( count($user_info) == 0 || $user_info[0]->password == '' ){
			return Response::json(['error'=>true , 'message'=>'第一次导入，请先选择手动同步，之后即可自动同步'] , 200);
		}
		$password = $user_info[0]->password;
		$number = $user_info[0]->number;


		$agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36';//伪装浏览器
		$library_ip = "202.206.242.99";
		$library_host = "http://202.206.242.99/";
		$library_pic_router = "reader/captcha.php";
		$library_login_router = "reader/redr_verify.php";

		$snoopy = new Snoopy;
		$submit_url = $library_host.$library_pic_router;

		//获取cookie
		$snoopy->host = $library_ip;
		$snoopy->agent = $agent;
		$snoopy->fetch($submit_url);
		$snoopy->setcookies();
		$cookie = $snoopy->cookies;
		//超时返回
		if ($snoopy->status != '200' || $snoopy->timed_out)
	    	return Response::json( ['error'=>true , 'message'=>'获取验证码失败'] , 200 );

		Session::put('pre_session' , $cookie['PHPSESSID']);
		$result = $snoopy->results;

		$filename = $user_id.'.png';
        $filepath = '/share/library/public/temp_img/'.$filename;

    	$size = strlen($result); //文件大小

    	$fp2 = @fopen( $filepath , 'a' );
    	fwrite( $fp2 , $result );
    	fclose( $fp2 );

        $output = shell_exec( 'tesseract '.$filepath.' /share/library/public/temp_text/'.$user_id.'.txt -l eng -psm 7' );
        $content = trim( file_get_contents( '/share/library/public/temp_text/'.$user_id.'.txt.txt' ) );

		if( strlen($content) != 4 ){
			return Response::json( ['error'=>true , 'message'=>'自动同步失败，请手动同步'] , 200 );
		}

        shell_exec( 'rm -rf '.$filepath );    //查完即删


		$submit_vars = array();
		$submit_vars['number'] 	= $number;
		$submit_vars['passwd'] 	= $password;
		$submit_vars['captcha'] = $content;
		$submit_vars['select'] 	= "cert_no";

		$snoopy = new Snoopy;
		$submit_url = $library_host.$library_login_router;

		//获取cookie
		$snoopy->host = $library_ip;
		$snoopy->agent = $agent;
		$snoopy->maxredirs = 0;
		$snoopy->referer = 'http://202.206.242.99/reader/redr_verify.php';
		$snoopy->cookies['PHPSESSID'] = Session::get('pre_session');

		$snoopy->submit($submit_url , $submit_vars);

		//超时返回
		if( $snoopy->timed_out ){
			return Response::json(['error'=>true , 'message'=>'同步超时，请重试'] , 200);
		}

		if ($snoopy->status > 0){
			//检查用户是否存在
			if( stripos($snoopy->results, "对不起，密码错误，请查实！") ){
				return Response::json(['error'=>true , 'message' => "对不起，密码错误，请查实！"] , 200);
			}else if( stripos($snoopy->results, "验证码错误(wrong check code)") ){
				return Response::json(['error'=>true , 'message' => "验证码错误(wrong check code)"] , 200);
			}else if( stripos($snoopy->results, "读者已经注销") ){
				return Response::json(['error'=>true , 'message' => "读者已被图书馆注销"] , 200);
			}else{
				//检查是否其他登录异常
				//获取个人证件信息
				$snoopy2 = new Snoopy;
				$snoopy2->host = "202.206.242.99";
				$snoopy2->referer = "http://202.206.242.99/reader/redr_verify.php";
				$snoopy2->agent = $agent;
				$snoopy2->cookies['PHPSESSID'] = Session::get('pre_session');
				//$snoopy->cookies['PHPSESSID'] = Input::get('pre_session');
				$snoopy2->fetch("http://202.206.242.99/reader/redr_info.php");

				$result2 = $snoopy2->results;
				if( $snoopy2->timed_out ){
					$this->forgetSession();
					return Response::json( ['error'=>true , 'message'=>'同步超时，请重试'] , 200 );
				}
				if( !stripos($snoopy2->results,"证件信息") ){
					$this->forgetSession();
					return Response::json( ['error'=>true , 'message'=>'图书馆登录失败，请登录学校图书馆网页版核实错误后再使用拾光登录'] , 200 );
				}

				$user_check = DB::table('user')->where('number','=',$number)->where('id','=',$user_id)->get();

				if( count($user_check) == 0 ){
					return Redirect::to('/');
				}else{
					$user_id = $user_check[0]->id;
					Session::put('lib_login' , 1);
					//之前总借阅册次
					$pre_all_books = $user_check[0]->count;
					//同步信息
					$update_result = $this->updateInfo($pre_all_books);

					if( $update_result >= 0 ){
						$now_time = date('Y-m-d H:i:s');
						DB::table('user')->where('id','=',$user_id)->update( array('sync_time'=>$now_time , 'password'=>$password) );
						return Response::json(['error'=>false , 'user_id'=>$user_id , 'message'=>'同步成功(2)'] , 200);
					}else{
						return Response::json(['error'=>true , 'user_id'=>$user_id , 'message'=>'同步失败，请重试'] , 200);
					}
				}
			}
		}else{
			return Response::json(['error'=>true , 'message'=>'同步失败(3)，请重试'] , 200);
		}

	}



	/**
     * @api {post} /login UserLogin
     * @apiVersion 0.1.0
     * @apiName UserLogin
     * @apiGroup User
     * @apiPermission app
     *
     * @apiDescription 用户模拟登陆图书馆
     *
     * @apiParam {Number} user_id 用户id.
     * @apiParam {String} username 用户名.
     * @apiParam {String} password 密码.
     * @apiParam {String} vcode 验证码.
     *
     * @apiSuccess {String} message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.179:82/login
     */

	 public function login(){

		 if( empty($_SESSION['user_id']) ){
 			return Response::json(['error'=>true , 'message'=>'请先登录或退出页面后重试'] , 200);
         }else{
			 if( !Input::has('username') || !Input::has('password') || !Input::has('vcode') )
	 	 		return Response::json(['error'=>true , 'message'=>'缺少重要参数'] , 200);

 			$user_id = $_SESSION['user_id'];
 			$arr = array(
 				'method' => 'POST' ,
 				'path' => 'login' ,
 				'query' => array(
					'username' => Input::get('username') ,
					'password' => Input::get('password') ,
					'code' => Input::get('vcode')
					)
 				);
 			$uri = Config::get('lib.ptime_api')."/user/".$user_id."/system_cat/library/api";
 			$verify = $this->curl_post( $uri , $arr , "campus" , "" );
 			$verify_result = json_decode($verify , true);

 			if( isset($verify_result['error']) ){
 				if( $verify_result['error'] ){
 					return Response::json(['error'=>true , 'message'=>'请求失败，暂时无法登录'] , 200);
 				}else{
 					return Response::json(['error'=>false , 'message'=>'登录成功'] , 200);
 				}
 			}
 		}

		// 	require_once app_path()."/libraries/Snoopy.class.php";
		//
		// 	//var_dump(Session::all());
		// if( !Session::has('user_id') ){
		// 	return Redirect::to('/');
		// }
		// 	if( !Input::has('username') || !Input::has('password') || !Input::has('vcode') )
	 // 		return Response::json(['error'=>true , 'message'=>'缺少重要参数'] , 200);
		//
		// 	$user_id 	= Session::get('user_id');
		// 	$username 	= Input::get('username');
		// 	$password 	= Input::get('password');
	 // 	$vcode 		= Input::get('vcode');
		// 	$session 	= Session::get('pre_session');
		//
	 // 	$agent 					= 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36';//伪装浏览器
		// $library_ip 			= "202.206.242.99";
		// $library_host 			= "http://202.206.242.99/";
		// $library_login_router 	= "reader/redr_verify.php";
		//
		// $submit_vars['number'] 	= $username;
		// $submit_vars['passwd'] 	= $password;
		// $submit_vars['captcha'] = $vcode;
		// $submit_vars['select'] 	= "cert_no";
		//
		// $snoopy = new Snoopy;
		// $submit_url = $library_host.$library_login_router;
		//
		// //获取cookie
		// $snoopy->host = $library_ip;
		// $snoopy->agent = $agent;
		// $snoopy->maxredirs = 0;
		// $snoopy->referer = 'http://202.206.242.99/reader/redr_verify.php';
		// $snoopy->cookies['PHPSESSID'] = Session::get('pre_session');
		//
		// $snoopy->submit($submit_url , $submit_vars);
		//
		// //超时返回
		// if( $snoopy->timed_out )
		// 	return Response::json(['error'=>true , 'message'=>'同步超时，请重试'] , 200);
		//
		// if ($snoopy->status > 0){
		// 	//检查用户是否存在
		// 	if( stripos($snoopy->results, "对不起，密码错误，请查实！") ){
		// 		return Response::json(['error'=>true , 'message' => "对不起，密码错误，请查实！"] , 200);
		// 	}else if( stripos($snoopy->results, "验证码错误(wrong check code)") ){
		// 		return Response::json(['error'=>true , 'message' => "验证码错误(wrong check code)"] , 200);
		// 	}else if( stripos($snoopy->results, "读者已经注销") ){
		// 		return Response::json(['error'=>true , 'message' => "读者已被图书馆注销"] , 200);
		// 	}else{
		// 		//检查是否其他登录异常
		// 		//获取个人证件信息
		// 		$snoopy2 = new Snoopy;
		// 		$snoopy2->host = "202.206.242.99";
		// 		$snoopy2->referer = "http://202.206.242.99/reader/redr_verify.php";
		// 		$snoopy2->agent = $agent;
		// 		$snoopy2->cookies['PHPSESSID'] = Session::get('pre_session');
		// 		//$snoopy->cookies['PHPSESSID'] = Input::get('pre_session');
		// 		$snoopy2->fetch("http://202.206.242.99/reader/redr_info.php");
		//
		// 		$result2 = $snoopy2->results;
		// 		if( $snoopy2->timed_out ){
		// 			$this->forgetSession();
		// 			return Response::json( ['error'=>true , 'message'=>'同步超时，请重试'] , 200 );
		// 		}
		// 		if( !stripos($snoopy2->results,"证件信息") ){
		// 			$this->forgetSession();
		// 			return Response::json( ['error'=>true , 'message'=>'图书馆登录失败，请登录学校图书馆网页版核实错误后再使用拾光登录'] , 200 );
		// 		}
		//
		// 		$user_check = DB::table('user')->where('number','=',$username)->where('id','=',$user_id)->get();
		// 		if( count($user_check) == 0 ){
		// 			// $new_id = DB::table('user')->insert(array('id'=>$user_id , 'number'=>$username , 'password'=>$password));
		// 			// if( $new_id > 0 ){
		// 			// 	Session::put('lib_login' , 1);
		// 			// 	Session::put('number' , $username);
		// 			// 	Session::put('password' , $password);
		// 			// 	return Response::json(['error'=>false , 'user_id'=>$user_id , 'message'=>'登录成功'] , 200);
		// 			// }else{
		// 			// 	return Response::json(['error'=>true , 'message'=>'登录失败(1)'] , 200);
		// 			// }
		// 			return Redirect::to('/');
		// 		}else{
		// 			$user_id = $user_check[0]->id;
		// 			Session::put('lib_login' , 1);
		// 			//之前总借阅册次
		// 			$pre_all_books = $user_check[0]->count;
		// 			//同步信息
		// 			$update_result = $this->updateInfo($pre_all_books);
		//
		// 			if( $update_result >= 0 ){
		// 				$now_time = date('Y-m-d H:i:s');
		// 				DB::table('user')->where('id','=',$user_id)->update( array('sync_time'=>$now_time , 'password'=>$password) );
		// 				return Response::json(['error'=>false , 'user_id'=>$user_id , 'message'=>'同步成功(2)'] , 200);
		// 			}else{
		// 				return Response::json(['error'=>true , 'user_id'=>$user_id , 'message'=>'同步失败，请重试'] , 200);
		// 			}
		// 		}
		// 	}
		// }else{
		// 	return Response::json(['error'=>true , 'message'=>'同步失败(3)，请重试'] , 200);
		// }
	 }



	 function updateInfo(){
		 $user_id = $_SESSION['user_id'];
		 $arr = array(
 			'method' => 'POST' ,
 			'path' => 'sync' ,
 			'query' => array()
 			);
 		$uri = Config::get('lib.ptime_api')."/user/".$user_id."/system_cat/library/api";
		//var_dump($uri);exit;
 		$verify = $this->curl_post( $uri , $arr , "campus" , "" );
 		$verify_result = json_decode($verify , true);
		//var_dump($verify);exit;

 		if( isset($verify_result['error']) ){
 			if( $verify_result['error'] ){
 				if( $verify_result['result'] == 'tokenNull' || $verify_result['result'] == 'tokenTimeOut' ){
					return Response::json(['error'=>true , 'result'=>'tokenNull'] , 200);
				}else{
					return Response::json(['error'=>true , 'result'=>'' , 'message'=>$verify_result['result']] , 200);
				}
 			}else{
				$current_time = date('Y-m-d H:i:s' , time());
				if( !empty($verify_result['result']['return_arr']) ){
					//更新个人信息
					$verify_result['result']['return_arr']['sync_time'] = $current_time;
					DB::table('user')->where('id','=',$user_id)->update($verify_result['result']['return_arr']);
				}
				if( !empty($verify_result['result']['current_rent_arr']) ){
					DB::table('user_rent')->where('user_id')->delete();
					//更新当前借阅数据
					foreach( $verify_result['result']['current_rent_arr'] as $key => $val ){
						$verify_result['result']['current_rent_arr'][$key]['user_id'] = $user_id;
					}
					DB::table('user_rent')->insert($verify_result['result']['current_rent_arr']);
				}
				if( !empty($verify_result['result']['history_arr']) ){
					DB::table('user_rent_history')->where('user_id')->delete();
					//更新历史借阅数据
					foreach( $verify_result['result']['history_arr'] as $key => $val ){
						$verify_result['result']['history_arr'][$key]['user_id'] = $user_id;
					}
					DB::table('user_rent_history')->insert($verify_result['result']['history_arr']);
				}
 				return Response::json(['error'=>false , 'result'=>$current_time , 'message'=>'同步成功'] , 200);
 			}
 		}else{
			return Response::json(['error'=>true , 'message'=>'同步失败' , 'result'=>[]] , 200);
 		}
	 }




	 //同步信息
	 public function updateInfo1( $pre_all_books ){
		require_once app_path()."/libraries/Snoopy.class.php";
 		require_once app_path()."/libraries/simple_html_dom.php";

		if( !Session::has('user_id') ){
			return -3;
		}
		$user_id = Session::get('user_id');

		$agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36';//伪装浏览器
	    $library_ip = "202.206.242.99";
	    $library_host = "http://202.206.242.99/";
	    $library_pic_router = "reader/redr_info.php";
	    $library_referer = "http://202.206.242.99/reader/redr_verify.php";

	    $indexInfoUrl = $library_host.$library_pic_router;

		//user表更新数组
		$update_arr = array();

	    //获取个人证件信息
	    $snoopy = new Snoopy;
	    $snoopy->host = $library_ip;
	    $snoopy->referer = $library_referer;
	    $snoopy->agent = $agent;
	    $snoopy->cookies['PHPSESSID'] = Session::get('pre_session');
	    $snoopy->fetch($indexInfoUrl);

	    $result = $snoopy->results;

	    if( $snoopy->timed_out ){
		    $this->forgetSession();
		    //return Response::json( ['error'=>true , 'message'=>'请求超时'] , 200 );
			return -1;
		}

	    if( !stripos($snoopy->results,"证件信息") ){
		    $this->forgetSession();
		    //return Response::json( ['error'=>true , 'message'=>'身份信息已失效 , 请重新登录'] , 200 );
			return -2;
		}

	    $html = new simple_html_dom();
	    $html->load( $result );
	    //用户姓名
	    $info_name = $html->find(".profile-name")[0]->innertext;

	    $info_detail = $html->find(".profile-info-value");
	    //证件开始时间
	    $info_detail_start_time = $info_detail[0]->children[0]->innertext;
	    //证件结束时间
	    $info_detail_end_time = $info_detail[1]->children[0]->innertext;
	    //email地址
	    $info_detail_email = $info_detail[2]->children[0]->innertext;

	    $info_data_number = $html->find(".infobox-data-number");

	    //超期图书数量
	    $info_data_outdate = $info_data_number[0]->innertext;
		$return_arr['out'] = $info_data_outdate;
		$update_arr['out'] = $info_data_outdate;
	    //委托到书数量
	    $info_data_let = $info_data_number[1]->innertext;
	    //预约到书数量
	    $info_data_order = $info_data_number[2]->innertext;
	    //荐购图书数量
	    $info_data_recom = $info_data_number[3]->innertext;

	    //超过多少人
	    $info_overpeople_num = $html->find(".Num")[0]->innertext;
	    $update_arr['over_num'] = $info_overpeople_num;

	    //获得称号
	    $info_level = $html->find("em")[0]->innertext;
	    $update_arr['level'] = $info_level;

	    $return_arr = array(
	 	   'name' => $info_name ,
	 	   'over_num' => $info_overpeople_num ,
		   'level' => $info_level ,
		   'range' => 'http://202.206.242.99/tpl/reader/chartPie.htm' ,
		   'time' => 'http://202.206.242.99/tpl/reader/chartColumn.htm',
		   );


	    //获取证件信息
	    $snoopy2 = new Snoopy;
	    $snoopy2->host = $library_ip;
	    $snoopy2->referer = "http://202.206.242.99/reader/redr_info.php";
	    $snoopy2->agent = $agent;
	    $snoopy2->cookies['PHPSESSID'] = Session::get('pre_session');
	    $snoopy2->fetch("http://202.206.242.99/reader/redr_info_rule.php");
	    $result2 = $snoopy2->results;

	    if( $snoopy2->timed_out || !stripos($result2,"证件信息") ){
	 	    $over_to_five = "";
		    $all_books_count = "";
		    $own_money = "";
	    }else{
		    $html2 = new simple_html_dom();
		    $html2->load($result2);
		    $book_nums = $html2->find("strong");

		    //五天内即将超期
		    $over_to_five = $book_nums[1]->innertext;
			$update_arr['five'] = $over_to_five;
		    //累计借书
		    $all_books_count = $html2->find("td")[12]->innertext;
		    //$temp_pos = stripos($all_books_count,"</span>");
		    $all_books_count_arr = explode("</span>", $all_books_count);
		    $all_books_count = $all_books_count_arr[1];
		    $all_books_count = substr(trim($all_books_count) , 0 , 2);
			$update_arr['count'] = $over_to_five;
		    //欠款金额
		    $own_money = $html2->find("td")[14]->innertext;
		    // $temp_pos = stripos($own_money,"</span>");
		    // $own_money = substr($own_money[1] , $temp_pos+7);
		    $own_money_arr = explode("</span>", $own_money);
		    $own_money = $own_money_arr[1];
			$update_arr['own'] = $own_money;
	    }

		//获取所有在借书籍
		$current_rent_arr = array();

		$snoopy2 = new Snoopy;
		$snoopy2->host = "202.206.242.99";
		$snoopy2->referer = "http://202.206.242.99/reader/book_lst.php";
		$snoopy2->agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
		$snoopy2->cookies['PHPSESSID'] = Session::get('pre_session');

		$target_url = "http://202.206.242.99/reader/book_lst.php";
		$snoopy2->fetch($target_url);

		$result = $snoopy2->results;

		if( $snoopy2->timed_out || !strpos($result , "当前借阅") ){
			//$this->forgetSession();
            return -4;
		}

		$html = new simple_html_dom();
		$html->load($result);
		$table_lines = $html->find(".table_line");
		if( count($table_lines) > 0 ){
			$table_line = $table_lines[0];
			$table_line_count = count($table_line);

			$all_trs = $table_line->find("tr");
			for( $i=1 ; $i < count($all_trs) ; $i++ ){
				$temp_tr = $all_trs[$i];
				$temp_tds = $temp_tr->find("td");

				//分析详情连接
				$temp_as = $temp_tds[1]->find("a");
				if( count($temp_as) > 0 ){
					$temp_as_href = $temp_as[0]->href;
					$target_detail_url = substr($temp_as_href , 8);
				}else{
					$target_detail_url = "";
				}

				//分析此借阅书的状态
				$book_state = "0";
				$temp_return = $temp_tds[3];
				$temp_font = $temp_return->find("font")[0]->color;
				if( $temp_font == 'red' ){
					$book_state = 1;
				}

				$renew_input = $temp_tr->find("input");
				if( count($renew_input) == 0 ){
					$temp_renew_code = "";
					$bar_code = "";
				}else{
					$getLib = $renew_input[0]->getAttribute("onclick");
					$checkCode_arr = explode(",", $getLib);
					$bar_code = substr($checkCode_arr[0] , 10 , 7);
					$checkCode = substr($checkCode_arr[1] , 1 , 8);
					$temp_renew_code = $checkCode;
				}
				$return_time = "";
				$temp_fonts = $temp_tds[3]->find("font");
				if( count($temp_fonts) > 0 ){
					$return_time = trim($temp_fonts[0]->innertext);
				}else{
					$return_time = trim($temp_tds[3]->innertext);
				}
				// $target_detail_url_arr = explode('/' , $target_detail_url);
				// if( count($target_detail_url) > 0 ){
				// 	$target_detail_url = $target_detail_url_arr[count($target_detail_url)-1];
				// }
				$current_rent_arr[] = array(
					'num' => $temp_tds[0]->innertext ,
					'name' => $temp_tds[1]->innertext ,
					'href' => $target_detail_url ,
					'rent_time' => trim($temp_tds[2]->innertext) ,
					'return_time' => $return_time ,
					'con_num' => $temp_tds[4]->innertext ,
					'location' => $temp_tds[5]->innertext ,
					'attach' => $temp_tds[6]->innertext ,
					'renew_code' => $temp_renew_code ,
					'bar_code' => $bar_code ,
					'state' => $book_state
					);
			}
		}


		if( count($current_rent_arr) > 0 ){
			$insert_arr = array();
			DB::table('user_rent')->where('user_id','=',$user_id)->delete();
			foreach( $current_rent_arr as $key => $val ){
				$insert_arr[] = array(
					'user_id' => $user_id ,
					'book_name' => $val['name'] ,
					'book_code' => $val['bar_code'] ,
					'book_href' => $val['href'] ,
					'book_location' => $val['location'] ,
					'rerent_num' => $val['con_num'] ,
					'rent_time' => $val['rent_time'] ,
					'return_time' => $val['return_time'] ,
					'attach' => $val['attach'] ,
					'bar_code' => $val['bar_code'] ,
					'check_code' => $val['renew_code'] ,
					'state' => $val['state']
					);
			}
			DB::table('user_rent')->insert($insert_arr);
		}

	    $return_arr['five'] = $over_to_five;
	    $return_arr['count'] = $all_books_count;
	    $return_arr['own'] = $own_money;
	    DB::table('user')->where('id','=',$user_id)->update($return_arr);

		if( $all_books_count > $pre_all_books ){
			//查找历史借阅书籍
			$snoopy = new Snoopy;
			$hist_url = "http://202.206.242.99/reader/book_hist.php";
			//$hist_url .= "?page=1";

			$snoopy->host = "202.206.242.99";
			$snoopy->agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
			$snoopy->cookies['PHPSESSID'] = Session::get('pre_session');
			$submit_vars = array(
				'para_string' => 'all' ,
				'topage' => '1'
				);
			$snoopy->submit($hist_url , $submit_vars);

			//超时返回
			if ($snoopy->status != '200' || $snoopy->timed_out){
				return -5;
			}

		    $result = $snoopy->results;

		    $html = new simple_html_dom();
		    $html->load($result);

		    $hist_arr = array();
			$table_line_1 = $html->find(".table_line");
			if( count($table_line_1) > 0 ){
				$table_line = $table_line_1[0];
			    $all_trs = $table_line->find("tr");

			    for( $i=1 ; $i<count($all_trs) ; $i++ ){
			    	$temp_tr = $all_trs[$i];
			    	$all_tds = $temp_tr->find("td");
			    	//分析详情连接
					$temp_as = $all_tds[2]->find("a");
					if( count($temp_as) > 0 ){
						$temp_as_href = $temp_as[0]->href;
						$target_detail_url = substr($temp_as_href , 8);
					}else{
						$target_detail_url = "";
					}
			    	//条码
			    	$num = $all_tds[1]->innertext;
			    	//标题
			    	$title = $all_tds[2]->innertext;
			    	//作者
			    	$author = $all_tds[3]->innertext;
			    	//借阅日期
			    	$rent_time = $all_tds[4]->innertext;
			    	//归还日期
			    	$return_time = $all_tds[5]->innertext;
			    	//馆藏地
			    	$location = $all_tds[6]->innertext;

					// $target_detail_url_arr = explode('/' , $target_detail_url);
					// if( count($target_detail_url) > 0 ){
					// 	$target_detail_url = $target_detail_url_arr[count($target_detail_url)-1];
					// }
			    	$hist_arr[] = array(
			    		'user_id' => $user_id ,
			    		'book_href' => $target_detail_url ,
			    		'book_name' => $title ,
			    		'book_author' => $author ,
			    		'rent_time' => $rent_time ,
			    		'return_time' => $return_time ,
			    		'book_location' => $location ,
						'book_code' => $num
			    		);
			    }
			    DB::table('user_rent_history')->where('user_id','=',$user_id)->delete();
				DB::table('user_rent_history')->insert($hist_arr);
			}
		}


	    //**
	    // 获取分人的rss令牌
	    // 先判断是否已存在rss令牌
	    $rss_token = "";
	    //$target_rss_exit = DB::table('user')->where('id','=',$user_id)->get();

	    //if( count($target_rss_exit) == 0 || $target_rss_exit[0]->rss == "" || $target_rss_exit[0]->rss == null ){
		    $snoopy3 = new Snoopy;
		    $snoopy3->host = $library_ip;
		    $snoopy3->agent = $agent;
		    $snoopy3->cookies['PHPSESSID'] = Session::get('pre_session');
		    $snoopy3->fetch("http://202.206.242.99/reader/redr_cust_result.php");
		    $result3 = $snoopy3->results;
		    if( !$snoopy3->timed_out ){
			    $temp_pos1 = strpos($result3 , "http://202.206.242.99:80/reader/rss.php?type=3&id=");
			    //DB::table('user')->where('id','=',$user_id)->update( array('rss'=>$result3) );
			    if( $temp_pos1 ){
				    $target_url_string = substr($result3 , $temp_pos1+50 , 48);
				    DB::table('user')->where('id','=',$user_id)->update( array('rss'=>$target_url_string) );
				    $rss_token = $target_url_string;
			    }
		    }
			DB::table('user')->where('id','=',$user_id)->update(array('rss'=>$rss_token));

	    //}else{
	    //	$rss_token = $target_rss_exit[0]->rss;
	    //}

		//超期图书本数
	    $temp_counter = 0;
	    if( $rss_token != "" ){
		    //直接请求rss接口
		    $rss_url = "http://202.206.242.99/reader/rss.php?type=3&id=".$rss_token;
		    //设置编码为UTF-8
		    $fp = fopen($rss_url , "r") or die("can not open $rss_url");
		    $buff = "";
		    while ( !feof($fp) ) {
		 	    $buff .= fgets($fp,4096);
		    }
		    //关闭文件打开
		    fclose($fp);
		    //建立一个 XML 解析器
		    $parser = xml_parser_create();
		    //xml_parser_set_option -- 为指定 XML 解析进行选项设置
		    xml_parser_set_option($parser , XML_OPTION_SKIP_WHITE , 1);
		    //xml_parse_into_struct -- 将 XML 数据解析到数组$values中
		    xml_parse_into_struct($parser , $buff , $values , $idx);
		    //xml_parser_free -- 释放指定的 XML 解析器
		    xml_parser_free($parser);
		    //header("Content-type:text/html;charset=utf-8");
		    //$values = mb_convert_encoding($values , "UTF-8//IGNORE" , "GB2312");
		    $is_item = -1;
		    $temp_counter = 0;
		    foreach( $values as $val ){
			    $tag = $val['tag'];
			    $type = $val['type'];
			    //$value = $val['value'];
			    //标签统一转为小写
			    $tag = strtolower($tag);
			    if( $tag == 'item' && $type == 'open' ){
				    $is_item = 1;
			    }else if( $tag == 'item' && $type == 'close' ){
				    $is_item = 0;
			    }
			    if( $is_item == 1 ){
				    if( $tag == 'title' ){
					    $temp_counter++;
				    }
			    }
		    }
	    }

		return 0;
	 }


	 /**
	  * 应用首页,返回基本数据
	  */
	 /**
     * @api {post} /offline UserIndexOffline
     * @apiVersion 0.1.0
     * @apiName UserIndexOffline
     * @apiGroup User
     * @apiPermission app
     *
     * @apiDescription 应用首页,返回基本数据(离线)
     *
     * @apiParam {Number} user_id 用户id.
     * @apiParam {String} number 账号.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {Object} result 用户信息对象.
     * @apiSuccess {String} result.id 用户id.
     * @apiSuccess {String} result.ptime_id 拾光id.
     * @apiSuccess {String} result.logo 用户头像.
     * @apiSuccess {String} result.name 用户姓名.
     * @apiSuccess {String} result.number 学号（用户名）.
     * @apiSuccess {String} result.password 密码.
     * @apiSuccess {String} result.email 邮箱.
	 * @apiSuccess {String} result.over_num 超过多少人.
     * @apiSuccess {String} result.level 等级.
     * @apiSuccess {String} result.five 五日即将超期.
     * @apiSuccess {String} result.count 借阅累计.
     * @apiSuccess {String} result.own 欠款.
     * @apiSuccess {String} result.update_time 上次更新时间.
     * @apiSuccess {String} message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.179:82/offline
     */
	public function check(){
		if( !Input::has('user_id') || !Input::has('number') )
			return Response::json(['error'=>true , 'message'=>'缺少重要参数'] , 200);
		$user_id 	= Input::get('user_id');
		$number 	= Input::get('number');

		$update_arr = array(
			'number' => $number
			);
		DB::table('user')->where('id','=',$user_id)->update($update_arr);

		$user_info = DB::table('user')->where('id','=',$user_id)->get();

		if( count($user_info) > 0 ){
			$temp_counter = 0;
			if( $user_info[0]->rss != "" ){
				$rss_token = $user_info[0]->rss;
				//直接请求rss接口
				$rss_url = "http://202.206.242.99/reader/rss.php?type=3&id=".$rss_token;
				//设置编码为UTF-8
				$fp = fopen($rss_url , "r") or die("can not open $rss_url");
				$buff = "";
				while ( !feof($fp) ) {
			        $buff .= fgets($fp,4096);
			    }
			    //关闭文件打开
			    fclose($fp);
			    //建立一个 XML 解析器
	    		$parser = xml_parser_create();
	    		//xml_parser_set_option -- 为指定 XML 解析进行选项设置
			    xml_parser_set_option($parser , XML_OPTION_SKIP_WHITE , 1);
			    //xml_parse_into_struct -- 将 XML 数据解析到数组$values中
			    xml_parse_into_struct($parser , $buff , $values , $idx);
			    //xml_parser_free -- 释放指定的 XML 解析器
			    xml_parser_free($parser);
			    $is_item = -1;
			    $temp_counter = 0;
			    foreach( $values as $val ){
			    	$tag = $val['tag'];
			    	$type = $val['type'];
			    	//$value = $val['value'];
			    	//标签统一转为小写
	        		$tag = strtolower($tag);
	        		if( $tag == 'item' && $type == 'open' ){
	        			$is_item = 1;
	        		}else if( $tag == 'item' && $type == 'close' ){
	        			$is_item = 0;
	        		}
	        		if( $is_item == 1 ){
	        			if( $tag == 'title' ){
	        				$temp_counter++;
	        			}
	        		}
			    }
			}
		}


		if( count($user_info) == 0 ){
			return Response::json( ['error'=>true , 'message'=>'用户信息出错'] , 200 );
		}else{
			return Response::json( ['error'=>false , 'result'=>$user_info[0], 'rss'=>$temp_counter ], 200 );
		}
	}


	//删除session
	public function forgetSession(){
		Session::forget('user_id');
		Session::forget('number');
		Session::forget('password');
	}



	//收藏图书
	public function collectBook(){
		if( empty($_SESSION['user_id']) ){
			return Response::json(['error'=>true , 'message'=>'请先登陆'] , 200);
		}
		if( !Input::has('user_id') || !Input::has('mac_no') ){
			return Response::json(['error'=>true , 'message'=>'缺少重要参数'] , 200);
		}
		$user_id = Session::get('user_id');
		$mac_no = Input::get('mac_no');

		$temp_no = $mac_no;
		$temp_no_length = strlen($temp_no);
		$temp_no_attach = "";
		if( $temp_no_length < 10 ){
			$split = 10 - $temp_no_length;
			for( $i=1 ; $i<=$split ; $i++ ){
				$temp_no_attach .= '0';
			}
			$temp_no = $temp_no_attach.$temp_no;
		}
		$mac_no = $temp_no;

		if( Input::has('is_cancel') && Input::get('is_cancel')==1 ){
			DB::table('user_collection')->where('user_id','=',$user_id)->where('mac_no','=',$mac_no)->delete();
			return Response::json(['error'=>false , 'message'=>'取消收藏成功'] , 200);
		}

		if( !Input::has('title') || !Input::has('author') || !Input::has('brief') || !Input::has('index') || !Input::has('press') || !Input::has('pic') ){
			return Response::json(['error'=>true , 'message'=>'缺少重要参数'] , 200);
		}

		$user_id 	= Input::get('user_id');
		$mac_no 	= Input::get('mac_no');
		$title 		= Input::get('title');
		$author 	= Input::get('author');
		$index 		= Input::get('index');
		$press 		= Input::get('press');
		$brief 		= Input::get('brief');
		$pic 		= Input::get('pic');

		if( $user_id < 1 || $mac_no == '' ){
			return Response::json(['error'=>true , 'message'=>'传入数据有误'] , 200);
		}

		$check = DB::table('user_collection')->where('user_id','=',$user_id)->where('mac_no','=',$mac_no)->get();
		if( count($check) == 0 ){
			$temp_href = "";
			$temp_no_length = strlen($mac_no);
			$temp_no_attach = "";
			if( $temp_no_length < 10 ){
                $split = 10 - $temp_no_length;
                for( $i=1 ; $i<=$split ; $i++ ){
                    $temp_no_attach .= '0';
                }
                $mac_no = $temp_no_attach.$mac_no;
            }
			$temp_href = "item.php?marc_no=".$mac_no;
			$insert_arr = array(
				'user_id' => $user_id ,
				'mac_no' => $mac_no ,
				'title' => $title ,
				'author' => $author ,
				'brief' => $brief ,
				'index' => $index ,
				'pic' => $pic ,
				'press' => $press
			);
			$insert_id = DB::table('user_collection')->insertGetId($insert_arr);
			if( $insert_id < 1 ){
				return Response::json(['error'=>true , 'message'=>'操作失败'] , 200);
			}else{
				return Response::json(['error'=>false , 'message'=>'关注成功'] , 200);
			}
		}else{
			DB::table('user_collection')->where('user_id','=',$user_id)->where('mac_no','=',$mac_no)->delete();
			return Response::json(['error'=>false , 'message'=>'取消关注成功'] , 200);
		}
	}

}
